﻿using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;

namespace RatingAuthor
{
  public class IndexedPagesBehaviour
  {
    private readonly string _indexedTamplateUrl;
    private readonly Func<int, bool> _predicate;
    private int _indexCounter;

    public IndexedPagesBehaviour(string indexedTamplateUrl, Func<int, bool> predicate)
    {
      _indexedTamplateUrl = indexedTamplateUrl;
      _predicate = predicate;
    }
    public Task<Page> Download()
    {
      int index;
      while (_predicate(index = Interlocked.Increment(ref _indexCounter) - 1)) { }

      var fileName = Path.GetTempFileName();
      return MyWebClient.DownloadFileAsync(GetUrl(index), fileName,
        e => Is404(e.Error) ? new Page() : new Page(fileName, index));
    }

    private static bool Is404(Exception x)
    {
      return x != null && x is WebException && x.Message.Contains("404");
    }
    private Uri GetUrl(int index)
    {
      return new Uri(string.Format(_indexedTamplateUrl, index == 0 ? null : "-" + (index + 1)));
    }

  }
}